/*
 * @lc app=leetcode.cn id=102 lang=cpp
 *
 * [102] 二叉树的层序遍历
 */

// @lc code=start
/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode() : val(0), left(nullptr), right(nullptr) {}
 *     TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
 *     TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
 * };
 */
class Solution {
public:
/**
 * @brief 
 * 
 * @param root 
 * @return vector<vector<int>> 
 
    vector<vector<int>> levelOrder(TreeNode* root) {
        vector<vector<int>> res;

        if (root == NULL)
        {
            return res;
        }

        vector<int> ans;
        queue<TreeNode*> q;
        TreeNode *p = NULL;
        q.push(root);
        while(!q.empty())
        {
            int size = q.size();
            ans.clear();
            for(int i = 0;i<size;i++)
            {
                p = q.front();
                q.pop();
                ans.push_back(p->val);

                if(p->left)
                {
                    q.push(p->left);
                }
                if(p->right)
                {
                    q.push(p->right);
                }
            }
            res.push_back(ans);
        }
        return res;
    }
*/

    void perorder(vector<vector<int>> &res,int depth,TreeNode *root)
    {
        if(!root)
            return;
        if(depth>=res.size())
            res.push_back(vector<int> {});
        res[depth].push_back(root->val);
        perorder(res,depth+1,root->left);
        perorder(res,depth+1,root->right);
    }

    vector<vector<int>> levelOrder(TreeNode* root) {
        vector<vector<int>> res;
        perorder(res,0,root);
        return res;
    }
};
// @lc code=end

